local redisLib = require "resty.redis"
local ip = '127.0.0.1'  
local port = '6379'
-- redis库
local dbNum = '2'
-- redis密码
local auth = '123456'
local timeout = 10000
local redis = redisLib:new()
redis:set_timeout(timeout)
if not redis then
  ngx.log(ngx.ERR, err)
  ngx.exec("@full")
end
local ck = require("cookie")
local http = require("socket.http")
local cjson = require("cjson")
local request_uri = ngx.var.request_uri
local arg = ""
local logpath = "/usr/local/nginx/logs/grey/"
local method = ngx.var.request_method
grey_cookie_key = "MXM_GREY"
cookie, err = ck:new()
-- 采集访问IP
function getClientIp()
        IP  = ngx.var.remote_addr 
        if IP == nil then
                IP  = "unknown"
        end
        return IP
end
-- 写入日志文件
function write(logfile,msg)
    local fd = io.open(logfile,"ab")
    if fd == nil then return end
    fd:write(msg)
    fd:flush()
    fd:close()
end
-- 记录灰度访问日志
function grep_log(method,url)
        local realIp = getClientIp()
        local ua = ngx.var.http_user_agent
        local servername=ngx.var.server_name
        local time=ngx.localtime()
        if ua  then
            line = realIp.." ["..time.."] \""..method.." "..servername..url.." \""..ua.."\"\n"
        else
            line = realIp.." ["..time.."] \""..method.." "..servername..url.."\"\n"
        end
        local filename = logpath..'/'..servername.."_"..ngx.today().."_grey.log"
        write(filename,line)
end
-- 获取cookie值
function get_cookies()
   local cookies = ngx.header["Set-Cookie"] or {}
   if type(cookie) == "string" then
     cookies = {cookies}
   end
   return cookies
end

-- 再原有cookie的基础上,添加新的cookie
function add_cookie(cookie)
   local cookies = get_cookies()
   table.insert(cookies, cookie)
   ngx.header['Set-Cookie'] = cookies
end

-- android登录APP,手机号码登录接口:'/api/login/validate/?phone=13814286681&smscode=7250',获取phone参数值。
local get_pattern = "^/api/login/validate/%?phone=[%d]+&smscode=[%d]+"
local post_pattern = "^/api/login/validate"
local field, err = cookie:get(grey_cookie_key)
--与redis服务器的连通性

local ok, err = redis:connect(ip, port)
if not ok then
   ngx.log("failed to connect:", err)
   ngx.exec("@full")
end
if auth ~= nil then
   --连接密码
   redis:auth(auth)
end
-- 选择操作的数据库
redis:select(dbNum)

--从redis中获取phone参数tags=13814286681 
local tags, err = redis:get(phone)
if not tags then
	ngx.log("failed to get phone: ", err)
	ngx.exec("@full")
end
if tags == ngx.null then
	ngx.log("phone not found.")
	ngx.exec("@full")
end
if method == "GET" and string.match(request_uri,get_pattern) ~= nil then
	local arg = ngx.var.arg_phone
	if arg == tags then
        if not field then
            --添加新鲜的cookie,并设置cookie的1天失效时间 
            add_cookie("MXM_GREY=1; Path=/; Expires=" .. ngx.cookie_time(ngx.time() + 86400))
        end 
        ngx.exec("@grey")
        --记录灰度记录的访问日志
        grep_log(method,request_uri) 
	else
        if not field then
            ngx.exec("@full")
        else
            -- 通过减少cookie失效时间来清除cookie
            add_cookie("MXM_GREY=1; Path=/; Expires=" .. ngx.cookie_time(0))
            ngx.exec("@full")
        end
	end

-- iphone登录APP,手机号码登录接口:'/api/login/validate';request_body：{'phone':'13814286681','smscode':'7250'},获取基于json格式上传的数据。
elseif method == "POST" and string.match(request_uri,post_pattern) ~= nil then
    local requestBody = ngx.unescape_uri(ngx.var.request_body)
    j = cjson.decode(requestBody)
    for key,value in pairs(j) do
		if key == "phone" then
          local arg = value
		end
    end
 	if arg == tags then
        if not field then
            --添加新鲜的cookie,并设置cookie的1天失效时间 
            add_cookie("MXM_GREY=1; Path=/; Expires=" .. ngx.cookie_time(ngx.time() + 86400))
        end 
        ngx.exec("@grey")
        --记录灰度记录的访问日志
        grep_log(method,request_uri) 
	else
        if not field then
            ngx.exec("@full")
        else
            -- 通过减少cookie失效时间来清除cookie
            add_cookie("MXM_GREY=1; Path=/; Expires=" .. ngx.cookie_time(0))
            ngx.exec("@full")
        end
	end      
else
    if not field then
        ngx.exec("@full")
    else
        ngx.exec("@grey")
    --记录灰度记录的访问日志
        grep_log(method,request_uri)
    end
end
http.TIMEOUT = 1
ngx.log(ngx.ERR)